<?php
/* 
 * HTML PreRENDER
 * version 3.0
 * this class can any change or proccess on template  and fill any control of form (Ex: text,radio,checbox,select,textarea,hidden) from Controler Layer.and change or remove content of tag 
 * 
 * for example:
 * $data = new Html('template.tpl');
 * $data->TextBox("fullname","mohamad reza kavoosi");
 * $data->innerHTML("DIV1","NEW CONTENT");
 * echo $data;
 * this part say to you that before load and echo HTML DATA CODE , find textBox with name="fullname" and set value of "mohamad reza kavoosi"  
 * for that automatically or find div with id='DIV1' and set new content for that.
 * 
 * Copyright (C) 2012 Mohamad Reza Kavoosi(spnuac@gmail.com)
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published 
 * by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. 
 */
class Html{

	private $dom;
	function __construct($filename=null,$templateString=null){
		$this->dom = new \DOMDocument('1.0',"utf-8");
		$this->dom->validateOnParse = false;
		$this->dom->strictErrorChecking = false;
		$this->dom->preserveWhiteSpace = false;
		libxml_use_internal_errors(true);
		if(!is_null($filename)) $this->LoadTemplate($filename);
		else if(!is_null($templateString)) $this->LoadTemplateString($templateString);
	}
	public function PostedDataToControls($REQUEST){
		if(isset($REQUEST)){
			foreach ($REQUEST as $name=>$value) {
				$el=$this->GetElement("name",$name);
				$el=$el->length >0 ?$el->item(0):null;
				$nodeName=$el->nodeName;
				switch (strtolower($nodeName)) {
					case "input":
						{
							$typeNode=$el->hasAttribute("type")? $el->getAttribute("type"):null;
							switch (strtolower($typeNode)) {
								case "radio":$this->Radio($name, $value);break;
								case "checkbox":$this->CheckBox($name);break;
								default:$this->TextBox($name, $value);break;
							}
						};break;
					case "textarea":$this->TextArea($name, $value);break;
					case "select":$this->DropDownList($name, $value);break;
				}
			}
		}
	}
	function LoadTemplate($fileAddress){
		return $this->DataToDom(file_get_contents($fileAddress));
	}
	function LoadTemplateString($data){
		return $this->DataToDom($data);
	}
	private function DataToDom($data){
		$this->dom->loadHTML($data);
	}
	public function AppendHead($value){
		$head= $this->dom->getElementsByTagName("head");
		if($head->length>0 && !empty($value)){
			$new = $this->dom->createDocumentFragment();
			$new->appendXML($value);
			$head->item(0)->appendChild($new); 
		}
	}
    public function Attribute($search,$attrName,$attrVal,$append=false){
        $el= $this->searchControls($search);
        if($el->length>0){
            for($i=0;$i<$el->length;$i++){
                $Attr= $append==false ?  $attrVal : $el->item($i)->getAttribute($attrName).$attrVal;
                $el->item($i)->setAttribute($attrName,$Attr);
            }
        }
    }
    public function titlePage($title){
        $t= $this->dom->getElementsByTagName("title");
        if($t->length>0)
            $t->item(0)->nodeValue = $title;
        else $this->AppendHead("<title>$title</title>");
	   $this->dom->loadHTML($this->__toString());   
    }
	public function AppendBody($value){
		$body= $this->dom->getElementsByTagName("body");
		if($body->length>0 &&  !empty($value)){
			$new = $this->dom->createDocumentFragment();
			$new->appendXML($value);
			$body->item(0)->appendChild($new); 
		}
	}
    private function searchControls($search){
        if($el=$this->GetElement("id",$search)) return $el;
        else if($el=$this->GetElement("class",$search)) return $el;
        else if($el=$this->GetElement("title",$search)) return $el;
        else return false;
    }
    
	public function removeTag($search){
	   $el=$this->searchControls($search);
       if($el->length>0){
            for($i=0,$c=$el->length;$i<$c;$i++){
        		$el->item($i)->parentNode->removeChild($el->item($i));
            }
       }
	}
	public function innerHTML($search,$Content,$append=true){
		$el=$this->searchControls($search);
		if($el->length>0 && !empty($Content)){
            for($i=0;$i<$el->length;$i++){
            	$dom= new \DOMCdataSection($Content);
                if($append==false)$el->item($i)->nodeValue="";
            	$el->item($i)->appendChild($dom); 
            }
    		$this->dom->loadHTML($this->__toString());
		}
	}
	public function TextBox($name,$value){
		$el=$this->GetElement("name",$name);
		if($el->length>0 ){
			$el= $el->item(0);
			$el->setAttribute("value", $value)	;
		}
	}
	public function DropDownList($name,$value){
		$el=$this->GetElement("name",$name);
        if($el->length>0){
    		foreach ($el->item(0)->childNodes as $node) {
    			if($node->hasAttribute("value") && $node->getAttribute("value")==$value)
    				$node->setAttribute ("SELECTED","SELECTED");
    			else if($node->hasAttribute("SELECTED")) $node->removeAttribute("SELECTED");
    		}
        }
	}
	public function TextArea($name,$value){
        $el=$this->GetElement("name",$name);
        if($el->length>0 && !empty($value)){
        	$new = $this->dom->createDocumentFragment();
        	$new->appendXML($value);
        	$el->item(0)->appendChild($new);
    		$this->dom->loadHTML($this->__toString());
        }
	}
	public function Radio($name,$value){
		$el=$this->GetElement("name",$name);
		foreach ($el as $node) {
			if($node->hasAttribute("value") && $node->getAttribute("value")==$value)
				$node->setAttribute ("checked","checked");
			else if($node->hasAttribute("checked")) $node->removeAttribute("checked");
		}
	}
	public function CheckBox($name,$checked=true){
		$el=$this->GetElement("name",$name);
        if($el->length>0){
    		if($checked) $el->item(0)->setAttribute("checked","checked");
    		else if($el->item(0)->hasAttribute("checked")) $el->item(0)->removeAttribute("checked");
        }
	}
	public function HiddenField($name,$value){
		$this->TextBox($name, $value);
	}
	private function GetElement($attr,$value){
		$xpath = new \DOMXpath($this->dom);
		$el = $xpath->query('//*[@'.$attr.'="'.$value.'"]');
		if($el->length>0)
			return $el;
		return false;
	}
    private function clearOutput(){
        $input=$this->dom->saveHTML();
		$input = preg_replace('/<input([^>\/]+)>/msU',"<input $1 />", $input);
		$input = preg_replace('/<br\s*>/msU',"<br/>", $input);
		$input = preg_replace('/<hr([^>]*)>/msU',"<hr $1 />", $input);
		$input = preg_replace('/<link([^>]*)>/msU',"<link $1 />", $input);
		$input = preg_replace('/<meta([^>]*)>/msU',"<meta $1 />", $input);
		if(strpos($input, "<html><body>")){
			$input=str_replace("<html><body>", "", $input);
			$input=str_replace("</body></html>", "", $input);
			$input = preg_replace('/^<\![^>]+>/', "", $input);
		}
        $this->dom->loadHTML($input);
        return $input;
    }
	function __toString(){
	   return $this->clearOutput() ;
	}
	
}